<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-28 16:21:26
 * @LastEditTime: 2020-02-27 09:37:39
 * @LastEditors: Please set LastEditors
 -->
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>Hello APP</title>
    <link rel="stylesheet" type="text/css" href="../../css/vant.css">
    <link rel="stylesheet" type="text/css" href="../../css/base.css" />
    <script type="text/javascript" src="../../script/jquery.js"></script>
    <script type="text/javascript" src="../../script/layer/mobile/layer.js"></script>
    <script type="text/javascript" src="../../script/vue.min.js"></script>
    <script type="text/javascript" src="../../script/vant.min.js"></script>
    <script type="text/javascript" src="../../script/fastclick.js"></script>
    <script type="text/javascript" src="../../script/base.js"></script>
    <script type="text/javascript" src="../../script/db.js"></script>
    <script type="text/javascript" src="../../script/moment.js"></script>
    <style type="text/css">
        .head {
            background: #ededed;
        }

        .van-nav-bar .van-icon {
            color: #000;
        }

        .van-nav-bar__title {
            color: #000;
            font-weight: 700;
        }

        .content {
            background: #fff !important;
        }

        .ul,
        li {
            padding: 0;
            margin: 0;
            list-style: none;
            display: block;
        }

        li:active {
            background: #e2e2e2;
        }

        .row {
            position: relative;
        }

        .header {
            width: 75px;
            height: 75px;
            padding: 15px;
            position: relative;
        }

        .header img {
            width: 100%;
            height: 100%;
            border-radius: 4px;
            overflow: hidden;
        }

        .label {
            position: absolute;
            top: 0;
            left: 75px;
            right: 0;
            height: 75px;
            border-bottom: 1px solid #efefef;
            padding: 15px 0;
        }

        .label .name {
            line-height: 25px;
            font-size: 16px;
            padding-right: 100px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            position: relative;
        }

        .label .name .time {
            position: absolute;
            top: 0;
            right: 0;
            padding-right: 15px;
            line-height: 26px;
            font-size: 12px;
            color: #a2a2a2;
        }

        .label .text {
            line-height: 19px;
            font-size: 14px;
            color: #a2a2a2;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            padding-right: 15px;
        }

        .un-read {
            width: 18px;
            height: 18px;
            border-radius: 9px;
            position: absolute;
            right: 6px;
            top: 6px;
            text-align: center;
            line-height: 18px;
            font-size: 12px;
            color: #fff;
            background: #cd1b21;
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
        <div class="init-full" @click="clickDom($event)">
            <van-nav-bar class="head" title="最近聊天" left-arrow @click-left="onClickLeft">
                <div slot="right" class="head-right">
                    <span @click.stop="showMenu = !showMenu">
                        <img src="../../image/menu-b.png" />
                    </span>
                </div>
            </van-nav-bar>
            <div class="body-no-bottom">
                <div class="content">
                    <div>
                        <ul>
                            <li v-for="(row,index) in chatPersonList" @click="intoDetail(row,index)">
                                <div class="row">
                                    <div class="header">
                                        <img :src="row.avatar?row.avatar:'../../image/we_header.png'" />
                                        <span class="un-read" v-show="row.unReadNum">{{row.unReadNum}}</span>
                                    </div>
                                    <div class="label">
                                        <div class="name">{{row.groupname || row.username}}<span class="time">{{getDateTime(row)}}</span>
                                        </div>
                                        <div class="text">
                                            <div v-html="returnHtml(row)"></div>
                                        </div>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
                <van-loading v-if="showLoading" />
            </div>
        </div>


        <div class="head-menu" v-if="showMenu">
            <img class="menu-arrow" src="../../image/menu-arrow.png" />
            <div @click="openFList">
                <img src="../../image/f-b.png" />
                <span>好友列表</span>
            </div>
            <div @click="createNewGroup">
                <img src="../../image/q-b.png" />
                <span>新建群聊</span>
            </div>
        </div>
    </div>
</body>

<script type="text/javascript">
    var vm;
    apiready = function () {

        api.addEventListener({
            name: 'keyback'
        }, function (ret, err) {
            vm.onClickLeft();
        });

        api.addEventListener({
            name: 'checkChatList'
        }, function (ret, err) {
            var msgObjArray = ret.value.msgObjArray;
            for (var i in msgObjArray) {
                if (msgObjArray[i].content) {
                    if (msgObjArray[i].type == 'group') {
                        msgObjArray[i].avatar = '../../image/ql.png';
                    }

                    var x = 0;
                    for (var j in vm.chatPersonList) {
                        if (parseInt(vm.chatPersonList[j].id) == parseInt(msgObjArray[i].id) && vm.chatPersonList[j].type == msgObjArray[i].type) {
                            x = 1;
                            msgObjArray[i].unReadNum = vm.chatPersonList[j].unReadNum + 1;
                            // vm.$set(vm.chatPersonList, j, msgObjArray[i]);

                            vm.chatPersonList.splice(j, 1);
                            vm.chatPersonList.unshift(msgObjArray[i]);
                            break;
                        }
                    }
                    if (x == 0) {
                        msgObjArray[i].unReadNum = 1;
                        vm.chatPersonList.unshift(msgObjArray[i]);
                    }
                }

            }
            vm.saveChat();

        })

        api.addEventListener({
            name: 'updateFriendReadTime'
        }, function (ret, err) {
            var chatID = ret.value.chatID;
            for (var i in vm.chatPersonList) {
                if (parseInt(vm.chatPersonList[i].id) == parseInt(chatID)) {
                    vm.chatPersonList[i].timestamp = ret.value.dateTime;
                }
            }
            vm.saveChat();
        })

        api.addEventListener({
            name: 'clearUnReadNum'
        }, function (ret, err) {
            var chatID = ret.value.chatID;
            for (var i in vm.chatPersonList) {
                if (parseInt(vm.chatPersonList[i].id) == parseInt(chatID)) {
                    vm.chatPersonList[i].unReadNum = 0;
                }
            }
            vm.saveChat();
        })

        api.addEventListener({
            name: 'deleteGroup'
        }, function (ret, err) {
            var groupId = ret.value.groupId;
            var deleteIndex = -1;
            for (var i in vm.chatPersonList) {
                if (parseInt(groupId) == parseInt(vm.chatPersonList[i].id)) {
                    deleteIndex = i;
                }
            }
            if (deleteIndex > -1) {
                vm.chatPersonList.splice(deleteIndex, 1);
            }
            vm.saveChat();

        })

        api.addEventListener({
            name: 'newGroup'
        }, function (ret, err) {
            var userIDArray = ret.value.userIDArray;
            userIDArray.push(FLD.getUserInfo().UserID)
            var groupName = ret.value.groupName;

            var obj = {
                groupName: groupName
            }
            FLD.ajax('insertNewGroup', obj, function (res) {
                var id = res.ds[0].groupId;
                var detailObj = {
                    groupId: id,
                    userIds: userIDArray.join(',')
                }
                FLD.ajax('joinGroup', detailObj, function (res) {
                    layer.open({
                        content: '群聊创建成功',
                        skin: 'msg',
                        time: 3
                    });
                    vm.chatPersonList.unshift({
                        groupname:groupName,
                        username: FLD.getUserInfo().UserName,
                        avatar: '../../image/ql.png',
                        id: id,
                        type: "group", //聊天窗口来源类型，从发送消息传递的to里面获取
                        content: '大家好,现在可以开始聊天了!',
                        cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
                        mine: true,  //是否我发送的消息，如果为true，则会显示在右方
                        fromid: FLD.getUserInfo().UserID,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
                        timestamp: moment().valueOf() //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
                    })
                    // window.localStorage.setItem('chatPersonList', JSON.stringify(vm.chatPersonList));
                    vm.saveChat();
                    api.sendEvent({
                        name: 'sendMineMsg',
                        extra: {
                            msgObj: {
                                content: '大家好,现在可以开始聊天了!',
                                toUserID: id.toString(),
                                type: 'group'
                            }
                        }
                    });

                })
            })
        })

        api.addEventListener({
            name: 'setLastChat'
        }, function (ret, err) {
            var chatID = ret.value.chatID;
            var msgObj = ret.value.msgObj;
            if (msgObj.type == 'group') {
                msgObj.avatar = '../../image/ql.png';
            }
            var x = 0;
            for (var i in vm.chatPersonList) {
                if (parseInt(vm.chatPersonList[i].id) == parseInt(chatID)) {
                    x = 1;
                    // vm.$set(vm.chatPersonList, i, msgObj);

                    vm.chatPersonList.splice(i, 1);
                    vm.chatPersonList.unshift(msgObj);
                    break;
                }
            }
            if (x == 0) {
                vm.chatPersonList.unshift(msgObj);
            }
            // window.localStorage.setItem('chatPersonList', JSON.stringify(vm.chatPersonList));
            vm.saveChat();
        })




        vm = new Vue({
            el: '#app',
            data: {
                showLoading: false,
                showMenu: false,
                chatPersonList: []
            },
            created: function () {
                var that = this;
                // if (window.localStorage.getItem('chatPersonList')) {
                //     that.chatPersonList = JSON.parse(window.localStorage.getItem('chatPersonList'));
                //     for (var i in that.chatPersonList) {
                //         that.chatPersonList[i].unReadNum = 0;
                //     }
                // }

                var sql = "select * from Chat where UserID='" + FLD.getUserInfo().UserID + "'";
                var chatPersonList_sql = DB.selectSqlSync(sql);
                if (chatPersonList_sql.length) {
                    that.chatPersonList = JSON.parse(chatPersonList_sql[0].JSONStr1);
                }
                for (var i in that.chatPersonList) {
                    that.chatPersonList[i].unReadNum = 0;
                }
                that.openChatList();
                that.getUnReadMsg();
            },
            methods: {
                clickDom(e) {
                    if (!$(e.target).closest('.head-menu').length) {
                        this.showMenu = false;
                    }
                },
                saveChat() {
                    var that = this;
                    var sql = "select * from Chat where UserID='" + FLD.getUserInfo().UserID + "'";
                    var chatPersonList_sql = DB.selectSqlSync(sql);
                    if (chatPersonList_sql.length) {
                        var sql = "update Chat set JSONStr1='" + JSON.stringify(that.chatPersonList).replace(/\'/g,'\'\'') + "',UpdateTime='" + FLD.getFormatDate() + "' where UserID='" + FLD.getUserInfo().UserID + "'";
                        DB.executeSql(sql, function () {

                        })
                    } else {
                        var sql = "insert into Chat (UserID,JSONStr1,CreateTime) values ('" + FLD.getUserInfo().UserID + "','" + JSON.stringify(that.chatPersonList).replace(/\'/g,'\'\'') + "','" + FLD.getFormatDate() + "')"
                        DB.executeSql(sql, function () {

                        })
                    }
                },
                openChatList() {
                    api.sendEvent({
                        name: 'openChatList',
                        extra: {
                            isOpenChatList: true
                        }
                    });
                },
                getDateTime(row) {
                    var that = this;
                    var rt = FLD.getChatFormatDate(new Date(moment(row.timestamp)))
                    return rt;
                },
                getUnReadMsg() {
                    api.sendEvent({
                        name: 'getUnReadMsgRepeat'
                    });
                },
                createNewGroup() {
                    var that = this;
                    that.showMenu = false;
                    api.openWin({
                        name: 'chatFriendList',
                        url: 'chatFriendList.html',
                        reload: true,
                        slidBackEnabled: false,
                        pageParam: {
                            isInvitation: 2
                        }
                    })
                },
                openFList() {
                    var that = this;
                    that.showMenu = false;
                    api.openWin({
                        name: 'chatFriendList',
                        url: 'chatFriendList.html',
                        reload: true,
                        slidBackEnabled: false
                    })
                },
                returnHtml(row) {
                    var that = this;
                    if (row.content.indexOf('语音消息') > -1 && row.content.indexOf('mp3_src') > -1) {

                        return '[语音消息]'
                    } else if (row.content.indexOf('img[') > -1) {
                        return '[图片]'
                    } else if (row.content.indexOf('openDetailFromMsg') > -1) {
                        return '[推送消息]'
                    } else {
                        return row.content;
                    }
                    // '[div mp3_src=' + mp3_path + ' onclick=playmp3(this)][div class=mp3_icon][/div][div style=display:inline-block;vertical-align: middle; ]语音消息[/div][/div]';

                },
                intoDetail(row, index) {
                    var that = this;
                    api.openWin({
                        name: 'chatListDetail',
                        url: 'chatListDetail.html',
                        reload: true,
                        slidBackEnabled: false,
                        pageParam: {
                            row: row
                        }
                    })

                },
                onClickLeft() {
                    api.sendEvent({
                        name: 'openChatList',
                        extra: {
                            isOpenChatList: false
                        }
                    });
                    api.closeWin();
                }
            }
        })
    }
</script>

</html>